/*
 * @lc app=leetcode.cn id=1870 lang=javascript
 *
 * [1870] 准时到达的列车最小时速
 */

// @lc code=start
/**
 * @param {number[]} dist
 * @param {number} hour
 * @return {number}
 */
var minSpeedOnTime = function (dist, hour) {
  if (dist.length > Math.ceil(hour)) return -1;
  let sum = dist.reduce((pre, cur) => pre + cur);
  let min = sum / hour;
  if (Number.isInteger(min)) return min;
  let ans = Math.floor(min);
  let l = ans,
    r = 10e10;
  let check = (ans) => {
    let sum = 0;
    for (let i = 0; i < dist.length; i++) {
      if (i !== dist.length - 1) {
        sum += Math.ceil(dist[i] / ans);
      } else sum += dist[i] / ans;
    }
    return sum <= hour;
  };
  while (l < r) {
    let mid = l + (r - l) / 2;
    if (check(mid)) {
      r = mid;
    } else {
      l = mid + 1;
    }
  }
  return l;
};
// @lc code=end
